package com.weisy.signin.ui.fragment;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.hjq.toast.ToastUtils;
import com.weisy.signin.R;
import com.weisy.signin.base.BaseFragment;
import com.weisy.signin.bean.MsgEvent;
import com.weisy.signin.bean.Sign;
import com.weisy.signin.bean.Student;
import com.weisy.signin.bean.Teacher;
import com.weisy.signin.comm.Comm;
import com.weisy.signin.network.WebConfig;
import com.weisy.signin.network.client.HttpClient;
import com.weisy.signin.network.resource.ScoreResourceUriHandler;
import com.weisy.signin.network.resource.SignResourceUriHandler;
import com.weisy.signin.network.server.HttpServer;
import com.weisy.signin.network.utils.StreamToolkit;
import com.weisy.signin.utils.DeviceUtils;
import com.weisy.signin.utils.GsonUtils;
import com.weisy.signin.utils.Logs;
import com.weisy.signin.utils.ShareUtils;
import com.weisy.signin.utils.SpUtils;
import com.weisy.signin.utils.TimeUtils;
import com.weisy.signin.widget.LoadingDialog;
import com.weisy.signin.widget.MsgDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yinshan.calendar.utils.Utils;
import com.yinshan.qrcode.activity.CaptureActivity;
import com.yinshan.qrcode.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Locale;

import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * @author weisy
 * @function 签到
 * @date 2019/3/21 21:22
 */
public class SignFragment extends BaseFragment {
    @BindView(R.id.img_sign_qrcode)
    ImageView imgQrCode;
    @BindView(R.id.line_sign_study)
    LinearLayout lineStudy;
    @BindView(R.id.line_sign_teach)
    LinearLayout lineTeach;
    @BindView(R.id.txt_sign_address)
    TextView txtAddress;
    @BindView(R.id.txt_sign_status)
    TextView txtStatus;
    @BindView(R.id.edit_sign_link)
    EditText editLink;
    @BindView(R.id.btn_sign)
    Button btnStop;

    private int userType;
    //老师签到配置
    private Teacher teacher;
    private WebConfig webServerConfig;
    private HttpServer server;
    //学生签到配置
    private Student student;
    private WebConfig webClientConfig;
    private HttpClient client;
    private LoadingDialog signDialog;

    private ShareUtils shareUtils;
    private String signLink;
    private Bitmap signBitmap;

    private MsgDialog msgDialog;

    @Override
    public int getLayoutId() {
        return R.layout.frag_sign;
    }

    @Override
    public void initViews(View view) {
        EventBus.getDefault().register(this);
        shareUtils = new ShareUtils(context);
        userType = (int) SpUtils.get(context, Comm.SP_TYPE, 1);
        if (userType == 1) {
            lineStudy.setVisibility(View.VISIBLE);
            lineTeach.setVisibility(View.GONE);
            btnStop.setVisibility(View.INVISIBLE);
        } else {
            lineStudy.setVisibility(View.GONE);
            lineTeach.setVisibility(View.VISIBLE);
            btnStop.setVisibility(View.VISIBLE);
        }
        signDialog = new LoadingDialog.Builder(context)
                .setBgDark(true)
                .setMsg("签到中...")
                .create();
    }

    @Override
    public void initDatas() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (SpUtils.contains(context, Comm.SP_PERION)) {
            String persion = (String) SpUtils.get(context, Comm.SP_PERION, "");
            if (userType == 1) {
                student = GsonUtils.str2Bean(persion, Student.class);
            } else {
                teacher = GsonUtils.str2Bean(persion, Teacher.class);
            }
        }
    }

    @OnClick({R.id.img_sign_qrcode, R.id.txt_sign_status, R.id.btn_sign_link, R.id.btn_sign_qrcode,
            R.id.img_sign_scan, R.id.img_sign_input, R.id.btn_sign})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.img_sign_qrcode:
                if (null == teacher || TextUtils.isEmpty(teacher.getCourse())) {
                    //教师信息不完整 不允许签到
                    showInfo("教师信息不完整，请补充完整再签到");
                    break;
                }
                if (null == server || !server.isEnable()) {
                    initServer();
                }
                break;
            case R.id.txt_sign_status:
                if (null != server && server.isEnable()) {
                    ARouter.getInstance().build(Comm.ROUTE_SIGN_LIST).navigation();
                } else {
                    ToastUtils.show("没有正在进行中的签到服务");
                }
                break;
            case R.id.btn_sign_link:
                //分享签到地址
                if (null == server || !server.isEnable()) {
                    ToastUtils.show("请启动签到服务后再来分享");
                    break;
                }
                shareUtils.shareUrl(signLink);
                break;
            case R.id.btn_sign_qrcode:
                //分享二维码
                if (null == server || !server.isEnable()) {
                    ToastUtils.show("请启动签到服务后再来分享");
                    break;
                }
                AndPermission.with(context)
                        .runtime()
                        .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE)
                        .onGranted(granted -> {
                            shareUtils.sharePic(signBitmap);
                        })
                        .onDenied(denied -> {
                            ToastUtils.show("分享图片需要文件读写权限");
                        }).start();
                break;
            case R.id.img_sign_scan:
                if (null == student || TextUtils.isEmpty(student.getName())) {
                    showInfo("学生信息不完整，请补充完整再签到");
                    break;
                }
                //扫码
                AndPermission.with(context)
                        .runtime()
                        .permission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE)
                        .onGranted(granted -> {
                            startActivityForResult(new Intent(context, CaptureActivity.class), 130);
                        })
                        .onDenied(denied -> {
                            ToastUtils.show("相机权限被禁止");
                        }).start();
                break;
            case R.id.img_sign_input:
                String link = editLink.getText().toString().trim();
                if (TextUtils.isEmpty(link)) {
                    ToastUtils.show("请输入签到地址");
                    return;
                }

                String ip = link.split("//")[1].split(":")[0];
                String port = link.split("//")[1].split(":")[1];
                webClientConfig = new WebConfig(ip, Integer.parseInt(port), 100);
                startSign();
                break;
            case R.id.btn_sign:
                if (null == server || !server.isEnable()) {
                    ToastUtils.show("没有进行中的签到");
                    break;
                }
                server.stopASync();
                server = null;
                imgQrCode.setImageResource(R.drawable.ic_default_qrcode);
                txtStatus.setText("没有签到服务");
                txtAddress.setText("点击二维码开始签到");
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 130) {
            if (resultCode == RESULT_OK) {
                String link = data.getStringExtra(CodeUtils.RESULT_STRING);
                Logs.d(TAG, "签到地址：" + link);
                if (!TextUtils.isEmpty(link)) {
                    editLink.setText(link);
                    String ip = link.split("//")[1].split(":")[0];
                    String port = link.split("//")[1].split(":")[1];
                    webClientConfig = new WebConfig(ip, Integer.parseInt(port), 100);
                    startSign();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(MsgEvent msgEvent) {
        switch (msgEvent.getCode()) {
            case Comm.SIGN_RESULT:
                if (null != signDialog && signDialog.isShowing()) {
                    signDialog.dismiss();
                }
                Logs.d(TAG, "result=" + msgEvent.toString());
                Sign sign;
                if (TextUtils.isEmpty(msgEvent.getMsg())) {
                    sign = GsonUtils.str2Bean(msgEvent.getData().toString(), Sign.class);
                    showSignResult(sign);
                } else {
                    sign = new Sign();
                    sign.setResult(msgEvent.getMsg());
                    showSignResult(sign);
                }
                //签到成功获取成绩
                if (null != webClientConfig) {
                    EventBus.getDefault().post(new MsgEvent(Comm.SIGN_WEBCONFIG, webClientConfig));
                }
                break;
            case Comm.SIGN_INFO:
                Sign sign1 = (Sign) msgEvent.getData();
                ToastUtils.show(sign1.getName() + "已签到");
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != server) {
            if (server.isEnable()) {
                server.stopASync();
            }
            server = null;
        }
        EventBus.getDefault().unregister(this);
        client = null;
        if (null != msgDialog) {
            if (msgDialog.isShowing()) {
                msgDialog.dismiss();
            }
            msgDialog = null;
        }
    }

    /**
     * 启动签到服务
     */
    private void initServer() {
        LoadingDialog loadingDialog = new LoadingDialog.Builder(context)
                .setBgDark(true)
                .setMsg("服务启动中...")
                .create();
        loadingDialog.show();
        webServerConfig = new WebConfig(StreamToolkit.getLocalIp(context), StreamToolkit.getPort(), 100);
        server = new HttpServer(webServerConfig);
        server.registerResourceHandler(new ScoreResourceUriHandler());
        server.registerResourceHandler(new SignResourceUriHandler(context));
        server.startASync();
        new Handler().postDelayed(() -> {
            if (loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
            Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher, null);
            signLink = String.format(Locale.CHINESE, "http://%s:%d", webServerConfig.getAddress(), webServerConfig.getPort());
            signBitmap = CodeUtils.createImage(signLink, 200, 200, logo);
            txtAddress.setText(signLink);
            imgQrCode.setImageBitmap(signBitmap);
            txtStatus.setText("签到中，点击查看签到列表");
            new LoadingDialog.Builder(context)
                    .setBgDark(true)
                    .setMsg("启动成功")
                    .setType(LoadingDialog.TYPE_SUCCESS)
                    .create().show();
        }, 1000);
    }

    private void startSign() {
        if (null == webClientConfig) {
            return;
        }
        signDialog.show();
        client = new HttpClient(webClientConfig);
        student.setDevice(DeviceUtils.getUniqueId(context));
        client.send("/", GsonUtils.bean2Str(student));
    }

    /**
     * 补充信息导航
     *
     * @param msg 学生或者老师提示
     */
    private void showInfo(String msg) {
        new MsgDialog.Builder(context)
                .setMsg(msg)
                .setBtnColor(ContextCompat.getColor(context, R.color.colorBlue))
                .setTxtRight("去添加", (DialogInterface.OnClickListener) (dialog, which) -> {
                    dialog.dismiss();
                    ARouter.getInstance().build(Comm.ROUTE_EDIT_INFO).withInt("userType", userType).navigation();
                })
                .setTxtLeft("取消", (dialog, which) -> {
                    dialog.dismiss();
                }).create().show();
    }

    /**
     * 签到结果返回
     */
    private void showSignResult(Sign sign) {
        String title;
        String msg;
        boolean isCenter;
        if (TextUtils.isEmpty(sign.getSignCourse())) {
            title = "签到失败";
            msg = sign.getResult();
            isCenter = true;
        } else {
            title = "签到成功";
            msg = "签到课程：" + sign.getSignCourse() + "\n" + "签到时间：" + TimeUtils.getCurrent();
            isCenter = false;
        }
        new MsgDialog.Builder(context)
                .setmTitle(title)
                .setMsg(msg)
                .setCenter(isCenter)
                .setBtnColor(ContextCompat.getColor(context, R.color.colorBlue))
                .setTxtLeft("知道了", (dialog, which) -> dialog.dismiss())
                .create().show();
    }
}
